package com.wmh.baseservice.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.entity.AdRole;
import com.wmh.baseservice.admin.entity.AdUserRole;
import com.wmh.baseservice.admin.pojo.vo.role.*;
import com.wmh.baseservice.admin.service.*;
import com.wmh.baseservice.admin.tools.enums.AdRoleEnum;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.common.utils.web.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 谢骏
 */
@Api(tags = "管理员-角色")
@RestController
@RequestMapping("admin/role")
@Validated
public class AdRoleController {

    @Resource
    private AdRoleService adRoleService;

    @Resource
    private AdInfoService adInfoService;

    @Resource
    private AdUserRoleService adUserRoleService;

    @Resource
    private AdRoleMenuService adRoleMenuService;

    @Resource
    private AdRoleRobotTaskService adRoleRobotTaskService;

    @Resource
    private UserUtil userUtil;

    @ApiOperation("添加角色V2")
    @PostMapping("addV2")
    @RequiresPermissions({"role.create"})
    public String addV2(@Valid AddRoleReqVO reqVO) {
        adRoleService.addV2(reqVO);
        return ReturnBody.success();
    }

    @ApiOperation("删除角色")
    @PostMapping("delete")
    @RequiresPermissions({"role.delete"})
    public String delete(String ids) {
        List<Long> idList = JSON.parseArray(ids, Long.class);
        adRoleService.delete(idList);
        return ReturnBody.success("删除角色成功");
    }

    @ApiOperation("修改角色状态")
    @PostMapping("updateStatus")
    @RequiresPermissions({"role.update"})
    public String updateStatus(@Valid @RequestBody UpdateStatusReqVO reqVO) {
        adRoleService.updateStatus(reqVO.getRoleId(), reqVO.getStatus());
        return ReturnBody.success("修改角色状态成功");
    }

    @ApiOperation("修改角色V2")
    @PostMapping("updateV2")
    @RequiresPermissions({"role.update"})
    public String updateV2(@Valid UpdateRoleReqVO reqVO) {
        if (AdRoleEnum.SUPER_ADMIN.getId().equals(reqVO.getId())) {
            throw new ServiceException("无法操作超级管理员权限");
        }
        adRoleService.updateV2(reqVO);
        return ReturnBody.success();
    }

    @ApiOperation("对角色给予菜单")
    @PostMapping("giveMenu")
    @RequiresPermissions({"role.giveMenu"})
    public String giveMenu(@Valid @RequestBody GiveMenuReqVO reqVO) {
        adRoleMenuService.setMenuIds(reqVO.getRoleId(), reqVO.getMenuIds());
        return ReturnBody.success();
    }

    @ApiOperation("提供可共选择的角色")
    @PostMapping("getBySelectRoleList")
    public String getBySelectRoleList() {
        List<AdRole> list = adRoleService.list();
        if (list == null) {
            throw new ServiceException("获取角色列表失败,系统异常请联系管理员");
        } else if (list.isEmpty()) {
            throw new ServiceException("获取角色列表时失败,数据库中没有角色请联系管理员");
        }
        // 过滤掉 账号已满的角色
        list = list.stream().filter(item ->
                adUserRoleService.count(new QueryWrapper<AdUserRole>().eq(AdUserRole.AD_ID, item.getId())) < item.getAccountNum()
        ).collect(Collectors.toList());
        return ReturnBody.success(list);
    }


    @ApiOperation("分页")
    @PostMapping("page")
    @RequiresPermissions({"role.query"})
    public String page(@Valid RolePageReqVO reqVO) {
        PageResult<AdRole> pageResult = new PageUtil<AdRole>(reqVO).startPage((page, queryWrapper) -> {
            queryWrapper.lambda()
                    .like(StrUtil.isNotBlank(reqVO.getName()), AdRole::getRoleName, reqVO.getName());
            adRoleService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("角色选项列表")
    @GetMapping("options")
    public String options() {
        List<AdRole> list = adRoleService.list(new QueryWrapper<AdRole>().select(AdRole.ID, AdRole.ROLE_NAME));
        return ReturnBody.success(list);
    }

    @ApiOperation("获取管理员角色列表")
    @PostMapping("getAdRoleList")
    public String getAdRoleList(@NotNull(message = "请提交管理员编号") Long adId) {
        return ReturnBody.success(adRoleService.getAdRolesByCache(adId, null));
    }

    @ApiOperation("获取角色拥有的任务列表")
    @GetMapping("robotTask")
    public String getRobotTask(@NotNull(message = "未提交角色编号") Long roleId) {
        return ReturnBody.success(adRoleRobotTaskService.getByRoleId(roleId));
    }
}
